<?php
namespace App\Console\Commands;

use App\Model\FromTradeDetailModel;
use App\Model\FromTradeModel;
use Illuminate\Console\Command;

use App\Model\BotsModel;
use App\Model\OutTradeModel;
use App\Service\SteamService;

class CheckFromTrade extends Command
{
	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $signature = 'check:fromtrade';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = '检查存入报价状态.';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->checkFromTradeAll();
        echo '数据查询完毕!'."\r\n";
        return true;
    }

	/**
	 * 多报价处理
	 * @return bool
	 */
	protected function checkFromTradeAll()
	{
		$trades = $this->getFromTradeByCheckAll();
		if (!$trades) {
			echo 'query waiting check for accept failed'."\r\n";
			return false;
		}

		foreach ($trades as $trade) {
			$this->checkFromTrade($trade['bot_id'], $trade);
		}

		return true;
	}

	/**
	 * 单报价处理
	 * @return bool
	 */
	protected function checkFromTrade($botId, array $trade)
	{
		$info = $this->getBotsInfoBybotId($botId);
		if (!$info) {
			echo 'query bots failed, botid: '.$botId."\r\n";
			return false;
		}

		$apiKey = $info['apikey'];
		$tradeofferId = $trade['tradeoffer_id'];

		$tradeoffer = SteamService::getInstance()->getTradeoffer($apiKey, $tradeofferId);
		if (!$tradeoffer) {
			echo 'query trade offer failed, tradeoffer_id:'.$trade['tradeoffer_id']."\r\n";
			return false;
		}
		$status = $tradeoffer['trade_offer_state'];

        // 处理暂挂
        if($status == FromTradeModel::$tradeOfferStatusMap['hang_up']){
            return FromTradeModel::updateFromTradeEscrowDate($trade['from_trade_id'], $tradeoffer['escrow_end_date']);
        }
        // 报价发起已确认,超时
        if($status == FromTradeModel::$tradeOfferStatusMap['create']){
            if(strtotime($trade['updated_at']) < (time() - 300)){
                return $this->cancelTrade($apiKey, $tradeofferId, $trade['from_trade_id']);
            }
        }

        if ($trade['tradeoffer_status'] != $status) {
			$this->updateFromTradeState($trade['from_trade_id'], $status);
		}

        // 成功
        if($status == FromTradeModel::$tradeOfferStatusMap['success']){
            $this->updateFromTradeState($trade['from_trade_id'], $status);
            if (isset($tradeoffer['tradeid'])){
                $this->setNewAssetId($trade, $apiKey, $tradeoffer['tradeid']);
            }
            return true;
        }

		if ($trade['tradeoffer_status'] == $status) {
			echo 'trade offer status no change, tradeofferid:'.$tradeofferId.', status: '.$status."\r\n";
			return false;
		}
		return true;
	}

    /**
     * 获取待检查的报价状态 (包括交易暂挂)
     * @return array
     */
    protected function getFromTradeByCheckAll()
    {
        return FromTradeModel::getFromTradeByCheckAll();
    }

    /**
     * 获取机器人信息
     * @param  int $botId 机器人ID
     * @return array
     */
    protected function getBotsInfoBybotId($botId)
    {
        return BotsModel::getBotsInfoBybotId($botId);
    }

    /**
     * 修改报价状态
     * @param  int $outTradeId 报价订单ID
     * @param  int $tradeofferStatus 报价状态
     * @return bool
     */
    protected function updateFromTradeState($fromTradeId, $tradeofferStatus)
    {
        return FromTradeModel::updateFromTradeState($fromTradeId, $tradeofferStatus);
    }

	/**
	 * 取消报价
	 * @param string $apiKey
	 * @param string $tradeofferId 报价ID
	 * @param int $outTradeId 取回报价ID
	 * @return bool
	 */
	protected function cancelTrade($apiKey, $tradeofferId, $outTradeId)
	{
		$res1 = SteamService::getInstance()->cancelTradeById($apiKey, $tradeofferId);
		if (!$res1) {
			echo 'steam cancel trade offer failed, tradeofferid: '.$tradeofferId."\r\n";
			return false;
		}

		$res2 = $this->updateFromTradeState($outTradeId, FromTradeModel::$tradeOfferStatusMap['canceled']);
		if (!$res2) {
			echo 'cancel trade offer failed, tradeofferid: '.$tradeofferId."\r\n";
			return false;
		}
		return true;
	}

    /**
     * 设置new_assetid
     * @param $apikey
     * @param $tradeId
     */
	protected function setNewAssetId(array $trade, $apikey, $tradeId)
    {
        $assets = SteamService::getInstance()->getTradeStatus($apikey, $tradeId);
        if (!$assets) {
            echo 'query trade offer status failed, tradeofferid: '.$trade['tradeoffer_id']."\r\n";
            return false;
        }

        foreach ($assets as $asset) {
            $asset = (array) $asset;
            $res = $this->updateNewAssetId($trade['from_trade_id'], $asset);
            if (!$res) {
                echo 'update order new assetid failed, orderid: '.$trade['from_trade_id']."\r\n";
                continue;
            }
            echo 'update order new assetid success'."\r\n";
        }
    }

    /*
     * 修改new_assetid
     */
    protected function updateNewAssetId($fromTradeId, $asset)
    {
        return FromTradeDetailModel::updateFromTradeDetailNewAssetId($fromTradeId, $asset);
    }
}